package one.three.thirtyNine;

public class RingBuffer<Item> {

	private Item[] a;
	private static final int size = 10;
	private int n;
	private int h = -1;
	private int t = -1;

	public synchronized boolean enqueue(Item item) {
		boolean r = false;
		if (a == null) {
			a = (Item[]) new Object[size];
			a[0] = item;
			h = 0;
			t = 0;
			n++;
			r = true;
		} else if (n < size) {
			if (t == a.length - 1) {
				t = 0;
				a[t] = item;
				n++;
			} else {
				t++;
				a[t] = item;
				n++;
			}
			r = true;
		}
		return r;
	}

	public Item dequeue() {
		if (a != null && n > 0) {
			Item r = a[h];
			if (h == a.length - 1) {
				h = 0;
			} else {
				h++;
			}
			n--;
			return r;
		}
		return null;
	}

	public static void main(String[] args) {
		RingBuffer<String> r = new RingBuffer<String>();
		r.enqueue("a");
		r.enqueue("b");
		r.enqueue("c");
		
		System.out.println(r.dequeue());
		System.out.println(r.n);
	}

}
